package com.xyh.controller.common;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xyh.base.RedisConstant;
import com.xyh.base.ResponseConstant;
import com.xyh.base.ResultAPI;
import com.xyh.base.WebContext;
import com.xyh.config.cache.RedisCache;
import com.xyh.config.security.vo.LoginUser;
import com.xyh.config.sysLog.SysLog;
import com.xyh.pojo.Log;
import com.xyh.pojo.User;
import com.xyh.service.FileUpLoadService;
import com.xyh.service.LogService;
import com.xyh.service.UserService;
import com.xyh.utils.FilePathUtil;
import com.xyh.utils.Utils;
import com.xyh.vo.request.other.UpdatePassReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * UserController的通用处理
 */
@Slf4j
@RequestMapping("/common/user/")
@RestController("userController")
public class UserController {

    private FileUpLoadService fileUpLoadService;
    private UserService userService;
    private LogService logService;
    private WebContext webContext;
    private RedisCache redisCache;
    private FilePathUtil util;

    @Value("${img.basePath}")
    private String basePath;

    @Autowired
    public UserController(FileUpLoadService fileUpLoadService, UserService userService, LogService logService,WebContext webContext,RedisCache redisCache,FilePathUtil util) {
        this.fileUpLoadService = fileUpLoadService;
        this.userService = userService;
        this.logService = logService;
        this.webContext = webContext;
        this.redisCache = redisCache;
        this.util = util;
    }

    @PostMapping("upload")
    @ResponseBody
    public ResultAPI<String> uploadImage(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        User currentUser = webContext.getCurrentUser();
        Integer userId = currentUser.getId();
        try {
            String path = fileUpLoadService.uploadFile(file);
            // 更新头像
            String url = Utils.filePath(path,request);
            userService.updateAvator(userId,path);
            // 更新redis中的数据
            String redisKey = RedisConstant.PREFIX + currentUser.getAccount();
            Object object = redisCache.getCacheObject(redisKey);
            LoginUser loginUser = JSON.parseObject(JSON.toJSONString(object), LoginUser.class);
            loginUser.getUser().setImagePath(url);
            redisCache.setCacheObject(redisKey,loginUser,180, TimeUnit.MINUTES);
            return new ResultAPI<>(200,"上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultAPI<>(ResponseConstant.FAILED,"上传失败","");
    }


    @GetMapping("current")
    public ResultAPI<User> getCurrent(){

        int userId = webContext.getCurrentUser().getId();
        User user = userService.getById(userId);
        user.setImagePath(util.getFileName(user.getImagePath()));
        return new ResultAPI<>(ResponseConstant.SUCCESS,"",user);
    }

    @PostMapping("updateSelf")
    public ResultAPI<String> updateSelf(@RequestBody User user){
        int userId = webContext.getCurrentUser().getId();
        user.setId(userId);
        userService.updateUser(user);
        return new ResultAPI<>(ResponseConstant.SUCCESS,"更新成功","");
    }

    @SysLog(content = "更新个人密码")
    @PostMapping("updatePass")
    public ResultAPI<String> updatePass(@RequestBody UpdatePassReqVO vo){
        int userId = webContext.getCurrentUser().getId();
        boolean flag = userService.updatePass(vo, userId);
        if(flag){
            return new ResultAPI<>(ResponseConstant.SUCCESS,"更新成功","");
        }
        return new ResultAPI<>(ResponseConstant.FAILED,"请检查旧密码是否输入正确","");
    }

    @GetMapping("log")
    @PreAuthorize("hasAnyRole('TEACHER','ADMIN')")
    public ResultAPI<IPage<Log>> getUserLog(){
        Integer userId = webContext.getCurrentUser().getId();
        IPage<Log> log = logService.getUserLog(userId);
        return new ResultAPI<>(ResponseConstant.SUCCESS,"成功",log);
    }


}
